package com.zshlong.seckill.util;

import com.alibaba.fastjson.JSON;
import com.zshlong.seckill.prefix.KeyPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * Redis常用操作工具类
 * */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /** 获取对象 */
    public Object get(KeyPrefix prefix, String key) {
        String realKey  = prefix.getPrefix() + key;
        return redisTemplate.opsForValue().get(realKey);
    }

    /** 设置对象 */
    public boolean set(KeyPrefix prefix, String key, Object value) {
        try {
            // 生成真正的key
            String realKey = prefix.getPrefix() + key;
            long seconds = prefix.expireSeconds();
            if(seconds <= 0) {
                redisTemplate.opsForValue().set(realKey, value);
            }else {
                redisTemplate.opsForValue().set(realKey, value, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /** 判断key是否存在 */
    @SuppressWarnings("all")
    public boolean exists(KeyPrefix prefix, String key) {
        try {
            String realKey  = prefix.getPrefix() + key;
            return redisTemplate.hasKey(realKey);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /** 删除 */
    public void delete(KeyPrefix prefix, String key) {
        //生成真正的key
        String realKey  = prefix.getPrefix() + key;
        if (realKey.length() > 0) {
            redisTemplate.delete(realKey);
        }
    }

    public void delete(KeyPrefix prefix) {
        if (prefix.getPrefix().length() > 0) {
            Set<String> keys = redisTemplate.keys(prefix.getPrefix()+"*");
            for (String key : keys) {
                redisTemplate.delete(key);
            }
        }
    }

    /** 增加值 */
    public Long incr(KeyPrefix prefix, String key) {
        //生成真正的key
        String realKey  = prefix.getPrefix() + key;
        return redisTemplate.opsForValue().increment(realKey);
    }

    /** 减少值 */
    public Long decr(KeyPrefix prefix, String key) {
        //生成真正的key
        String realKey  = prefix.getPrefix() + key;
        return redisTemplate.opsForValue().decrement(realKey);
    }

}
